<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showAddEmployeeDialog">新增员工</el-button>
        </template>
      </page-tools>
      <el-card v-loading="loading" style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" :index="indexMethod" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{ row }">
              <img v-imgerror="errimg" :src="row.staffPhoto || defaultImage" class="staff" @click="showImgDialogfn(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="getEmploymentText"
          >
            <!-- <template #default="{ row }">
              {{ getEmploymentText(row.formOfEmployment) }}
            </template> -->
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{row}">
              {{ row.timeOfEntry | getFormateTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                :disabled="!checkPermission('POINT-USER-UPDATE')"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" :disabled="!checkPermission('POINT-USER-UPDATE')" @click="showEditRoleDialogFn(row.id)">角色</el-button>
              <el-button type="text" size="small" :disabled="!checkPermission('point-user-delete')" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="size"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <!-- 使用弹层组件 -->
      <add-employee :show-dialog.sync="showDialog" @add-success="getEmployeeList" />
      <el-dialog title="二维码图片" :visible="showCodeDialog" :close-on-click-modal="false" @close="hideCodeDialogFn">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeListApi, delEmployeeApi } from '@/api/employee'
import EmployeeEnum from '@/constant/employees'
import AddEmployee from './components/add-employee'
import { getFormateTime } from '@/filters'
import errimg from '@/assets/404_images/404.webp'
import QrCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
import { mapGetters } from 'vuex'
import checkPermission from '@/mixins/check'
// import dayjs from 'dayjs'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  mixins: [checkPermission],
  // 过滤器采用全局注册的方式
  // filters: {
  //   getFormateTime(val) {
  //     return dayjs(val).format('YYYY-MM-DD')
  //   }
  // },
  data() {
    return {
      list: [],
      page: 1, // 当前页
      size: 10, // 每页条数
      total: 0, // 总数
      loading: false,
      showDialog: false,
      defaultImage: 'https://img2.baidu.com/it/u=2203692359,101708973&fm=253&fmt=auto&app=138&f=PNG?w=401&h=401',
      errimg: errimg,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { data } = await getEmployeeListApi(this.page, this.size)
      // console.log(data)
      this.loading = false
      const { rows, total } = data
      this.total = total
      this.list = rows
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeList()
    },
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
    },
    // 利用作用域插槽格式化
    // getEmploymentText(num) {
    //   return num === 1 ? '正式员工' : '正式员工'
    // }
    // 利用formatter格式化
    getEmploymentText(row, column, cellValue, index) {
      // return cellValue === 1 ? '正式员工' : '正式员工'
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    delEmployee(id) {
      this.$confirm('亲!您确定要删除吗?', '温馨提示').then(async() => {
        await delEmployeeApi(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('恭喜,删除成功')
        this.getEmployeeList()
      }).catch(() => {})
    },
    showAddEmployeeDialog() {
      this.showDialog = true
    },
    async exportExcel() {
      // 请注意: 如果导出的是当前页, 那么数据, this.list 即可,
      // 但是我们一般导出的是全部的数据, 需要请求到所有的数据
      const { data: { rows }} = await getEmployeeListApi(1, this.total)
      // console.log(rows)
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const exportData = this.formateExportData(rows, headersArr, headersRelations)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // 表头 必填
          data: exportData, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    /**
     * 将数据处理为二维数组
     * @param {*} rows  所有数据
     * @param {*} headersArr  表头
     * @param {*} headersRelations  对应关系
     */
    formateExportData(rows, headersArr, headersRelations) {
      const result = []
      rows.forEach(item => {
        const arr = []
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = item[englishKey] ? getFormateTime(item[englishKey]) : ''
          }
          if (englishKey === 'fromOfEmployMent') {
            const obj = EmployeeEnum.hireType.find(enumObj => enumObj.id === item[englishKey])
            value = obj ? obj.value : '未知'
          }
          arr.push(value)
        })
        result.push(arr)
      })
      return result
    },
    /**
     * 点击头像控制弹层显示和隐藏
     */
    showImgDialogfn(url) {
      if (!url) {
        this.$message.error('当前用户没有头像')
        return
      }
      this.showCodeDialog = true
      // 通过$nextTick等dom完全加载出来再显示
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    hideCodeDialogFn() {
      this.showCodeDialog = false
    },
    showEditRoleDialogFn(id) {
      this.showRoleDialog = true
      this.userId = id
    }

  }
}
</script>

<style lang="scss" scoped>
.employees-container {
    .staff {
      width: 70px;
      height: 70px;
      border-radius: 50%;
    }
  }
</style>
